<?php
/**
 * Created by PhpStorm.
 * User: czw
 * Date: 2018/7/11
 * Time: 14:59
 */
namespace app\common\model;

use app\lib\exception\BaseException;
use app\lib\exception\CreateException;
use app\lib\exception\NotFoundException;
use app\lib\exception\UpdateException;
use think\Db;

class Product extends BaseModel
{
    protected $field = true;
    protected $hidden = ['delete_time'];

    public function getImgUrlAttr($value)
    {
        return config('common.img_url') . $value;
    }
    public function getStartTimeAttr($value)
    {
        return $value?date('Y-m-d',$value):'';
    }
    public function getEndTimeAttr($value)
    {
        return $value?date('Y-m-d',$value):'';
    }
    public function piece()
    {
        return $this->hasMany('ProductPiece')->order('sort ASC');
    }

    public static function createOne($data)
    {
        $model = new self();
        $res = $model->allowField(true)->save($data);
        if (!$res) throw new CreateException();
        return $model;
    }

    /**
     * 获取产品列表
     * @param array $where
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getAll($where = [])
    {
        $res = self::where($where)->select();
        return $res;
    }

    public static function getById($id)
    {
        $res = self::with('piece')->find($id);
        if (!$res) throw new NotFoundException();
        return $res;
    }

    public static function deleteOne($id)
    {
        $product = Db::table('__PRODUCT__')->where('id='.$id)->find();
        if(!$product) throw new BaseException(['msg'=>'无此商品！']);
        //商品超出兑换期一个月可软删除
        if(($product['end_time']+3600*24*30) >time()){
            throw new BaseException(['msg'=>'活动结束后一个月才可删除商品！']);
        }
        return self::destroy($id);
    }

    public static function updateOne($id, $data)
    {
        $model = new self();
        $res = $model->data($data)->update($data, ['id' => $id]);
        if (!$res) throw new UpdateException(['msg'=>'保存失败！']);
        return $model;
    }

}